<?

class lego_paginator extends lego_abstract{
	private $total;
	private $pagesize;
	private $pagecount;
    public function getDir(){return dirname(__FILE__);}
    
    
    static public function lazy(DQ $q){
    	$old_fields = $q->fields();
    	$total = $q->fields("count(*)")->value(true);
    	$lego = new self($total, $q->limit());
    	$lego->run();
    	$q->offset($q->limit() * $lego->getCurrentPage(true));
    	$q->fields($old_fields);
    	Output::assign("paginator" , $lego);
	}
    
    public function __construct($total = 60, $pagesize = 20){
    	$this->total = $total;
    	$this->pagesize = $pagesize;
    	$this->pagecount = ceil($total/$pagesize);
        parent::__construct();
    }
    
    public function getTotal(){return $this->total;}
    public function getPagesize(){return $this->pagesize;}
    public function getPagecount(){return $this->pagecount;}
    
    function getCurrentPage($from_zero = false){
    	$page = $this->runner()->getLegoParam("page");
    	if(!$page) $page = 1;
    	if($page > $this->pagecount) $page = 1;
    	if($from_zero) --$page;
    	return $page;
	}
	
	function getOffset(){
		return $this->getCurrentPage(true) * $this->getPagesize();
	}
    
    function action_index(){
    	$visible_pages = 3;
    	$central = ceil($visible_pages/2);
    	$count_before = $visible_pages - $central;
    	$range_start = $this->getCurrentPage() - $count_before;
    	if($range_start < 1) $range_start = 1;
    	$range_end = $range_start + $visible_pages - 1;
    	if($range_end > $this->getPagecount()) $range_end = $this->getPagecount();
    	Output::assign("range", range($range_start, $range_end));
    	return $this->fetch("lego_paginator.tpl");
	}
}
?>